package com.idea.relax.log.support.utils;

import ch.qos.logback.classic.AsyncAppender;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.filter.LevelFilter;
import ch.qos.logback.classic.filter.ThresholdFilter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.FileAppender;
import ch.qos.logback.core.rolling.RollingPolicy;
import ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy;
import ch.qos.logback.core.spi.FilterReply;
import ch.qos.logback.core.util.FileSize;
import com.idea.relax.log.props.LogLevel;
import org.slf4j.LoggerFactory;
import org.springframework.boot.logging.logback.LogbackLoggingSystemProperties;
import static ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME;

/**
 * 参考自 jhipster
 * <p>
 * Utility methods to add appenders to a {@link LoggerContext}.
 *
 * @author jhipster
 * @author L.cm
 */
public class LoggingUtil {
	public static final String DEFAULT_LOG_DIR = "logs";

	public static final String LOG_FILE_ALL = "all.log";

	public static final String LOG_FILE_INFO = "info.log";

	public static final String LOG_FILE_ERROR = "error.log";

	public static final String CONSOLE_APPENDER_NAME = "CONSOLE";

	public static final String FILE_APPENDER_NAME = "FILE";

	public static final String FILE_ERROR_APPENDER_NAME = "FILE_ERROR";

	public static final String DEFAULT_FILE_LOG_PATTERN = "${FILE_LOG_PATTERN:%d{${LOG_DATEFORMAT_PATTERN:yyyy-MM-dd HH:mm:ss.SSS}} ${LOG_LEVEL_PATTERN:%5p} ${PID:} --- [%t] %-40.40logger{39} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:%wEx}}";

	public static final String DEFAULT_CONSOLE_LOG_PATTERN = "${CONSOLE_LOG_PATTERN:%d{yyyy-MM-dd HH:mm:ss.SSS}|%highlight(%-5level)|%boldYellow(%thread)|%boldGreen(%logger)|%msg%n}";

	/**
	 * detach appender
	 *
	 * @param name appender name
	 */
	public static void detachAppender(String name) {
		LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
		context.getLogger(ROOT_LOGGER_NAME).detachAppender(name);
	}

	public static RollingPolicy rollingPolicy(LoggerContext context,
											  FileAppender<?> appender,
											  String logFile) {
		final SizeAndTimeBasedRollingPolicy<ILoggingEvent> rollingPolicy = new SizeAndTimeBasedRollingPolicy<>();
		rollingPolicy.setContext(context);
		rollingPolicy.setCleanHistoryOnStart(SystemUtil.getPropToBool(LogbackLoggingSystemProperties.ROLLINGPOLICY_CLEAN_HISTORY_ON_START, false));
		rollingPolicy.setFileNamePattern(logFile + ".%d{yyyy-MM-dd}.%i.gz");
		rollingPolicy.setMaxFileSize(FileSize.valueOf(SystemUtil.getProp(LogbackLoggingSystemProperties.ROLLINGPOLICY_MAX_FILE_SIZE, "10MB")));
		rollingPolicy.setMaxHistory(SystemUtil.getPropToInt(LogbackLoggingSystemProperties.ROLLINGPOLICY_MAX_HISTORY, 15));
		rollingPolicy.setTotalSizeCap(FileSize.valueOf(SystemUtil.getProp(LogbackLoggingSystemProperties.ROLLINGPOLICY_TOTAL_SIZE_CAP, "0")));
		rollingPolicy.setParent(appender);
		rollingPolicy.start();
		return rollingPolicy;
	}

	public static AsyncAppender bindAsyncAppender(Appender<ILoggingEvent> newAppender,int queueSize,
												  int discardingThreshold,boolean neverBlock){
		AsyncAppender asyncAppender = new AsyncAppender();
		asyncAppender.setQueueSize(queueSize);
		asyncAppender.setDiscardingThreshold(discardingThreshold);
		asyncAppender.setNeverBlock(neverBlock);
		asyncAppender.addAppender(newAppender);
		return asyncAppender;
	}


	public static LevelFilter levelFilter(LoggerContext context, LogLevel level) {
		final LevelFilter filter = new LevelFilter();
		filter.setContext(context);
		filter.setLevel(level.getLevel());
		filter.setOnMatch(FilterReply.ACCEPT);
		filter.setOnMismatch(FilterReply.DENY);
		filter.start();
		return filter;
	}

	public static ThresholdFilter thresholdFilter(LoggerContext context, LogLevel level) {
		final ThresholdFilter filter = new ThresholdFilter();
		filter.setContext(context);
		filter.setLevel(level.getLevel().levelStr);
		filter.start();
		return filter;
	}


}
